package com.kristin.netty;


import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.FutureRequestExecutionService;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.HttpRequestFutureTask;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainTest {

    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    private List<HttpRequestFutureTask<String>> tasks = new ArrayList<>();

    private static final class OkidokiHandler implements ResponseHandler<String> {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            // 2.1处理响应结果
            return EntityUtils.toString(response.getEntity());
        }
    }

    private static final class MyCallback implements FutureCallback<String> {

        public void failed(final Exception ex) {
            System.out.println(ex.getLocalizedMessage());
        }

        public void completed(final String result) {
            System.out.println(result);
        }

        public void cancelled() {
            System.out.println("cancelled");
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 4.创建FutureRequestExecutionService实例
        FutureRequestExecutionService futureRequestExecutionService = new FutureRequestExecutionService(httpclient, executorService);
        try {
            // 5.1请求参数
            for(int i = 0 ; i < 10 ; i++) {
                HttpGet get = new HttpGet("http://127.0.0.1:8080/test");
                HttpRequestFutureTask<String> task = futureRequestExecutionService.execute(get,
                        HttpClientContext.create(), new OkidokiHandler(), new MyCallback());
            }
        } finally {
            httpclient.close();
        }
        Thread.sleep(10000);

    }



}
